package com.qqpz.sign_project.controller;

import com.google.gson.Gson;
import com.qqpz.sign_project.entity.Goods;
import com.qqpz.sign_project.entity.User;
import com.qqpz.sign_project.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/v1/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping("/")
    public String queryAllGoods() {
        List<Goods> list = goodsService.queryAllGoods();
        Map<String,Object> map=new HashMap<>();
        if(list!=null){
            map.put("result","success");
            map.put("goods",list);
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }

    }

    @PostMapping("/")
    public String createGoods(@RequestBody Goods goods){
        int i = 0;
        try {
            i = goodsService.createGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
            i=0;
        }
        Map<String,Object> map=new HashMap<>();
        if(i!=0){
            map.put("result","success");
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }
    }
    @PostMapping("/update")
    public String updateGoodsById(@RequestBody Goods goods){
        int i = 0;
        try {
            i = goodsService.updateGoodsById(goods);
        } catch (Exception e) {
            e.printStackTrace();
            i=0;
        }
        Map<String,Object> map=new HashMap<>();
        if(i!=0){
            map.put("result","success");
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }
    }
    @PostMapping("/delete")
    public String deleteGoodsById(@RequestBody Goods goods){
        int i = 0;
        try {
            i = goodsService.deleteGoodsById(goods.getId());
        } catch (Exception e) {
            e.printStackTrace();
            i=0;
        }
        Map<String,Object> map=new HashMap<>();
        if(i!=0){
            map.put("result","success");
            return new Gson().toJson(map);
        }else{
            map.put("result","fail");
            return new Gson().toJson(map);
        }
    }

}
